package com.qupai.lib_base.app

import android.app.Application
import android.content.Context
import androidx.core.content.ContextCompat
import androidx.multidex.MultiDex
import com.blankj.utilcode.util.DeviceUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.blankj.utilcode.util.Utils
import com.drake.net.NetConfig
import com.drake.net.interceptor.LogRecordInterceptor
import com.drake.net.interceptor.RequestInterceptor
import com.drake.net.okhttp.setConverter
import com.drake.net.okhttp.setDebug
import com.drake.net.okhttp.setDialogFactory
import com.drake.net.okhttp.setRequestInterceptor
import com.drake.net.request.BaseRequest
import com.drake.tooltip.dialog.BubbleDialog
import com.hjq.language.MultiLanguages
import com.kongzue.dialogx.DialogX
import com.proembed.service.MyService
import com.qupai.lib_base.BuildConfig
import com.qupai.lib_base.R
import com.qupai.lib_base.convert.SerializationConverter
import com.qupai.lib_base.utils.nds.AliDnsUtils
import com.qupai.lib_base.utils.nds.OkHttpDns
import com.tencent.mmkv.MMKV
import okhttp3.Cache
import java.util.concurrent.TimeUnit

open class BaseApplication : Application() {

    companion object {
        lateinit var psaApp: BaseApplication
        lateinit var myService: MyService
        var isDebug = false
    }

    override fun attachBaseContext(base: Context?) {
        super.attachBaseContext(MultiLanguages.attach(base))
        MultiDex.install(this)
    }

    override fun onCreate() {
        super.onCreate()
        psaApp = this
    }

    /**
     * Init utils and net
     * 初始化工具和网络请求
     * @param debug 开发环境
     * @param baseUrl 基地址
     * @param deviceSerial 设备序列号
     * @param dnsHostNames 需要加阿里云公共DNS解析的地址组
     * @param isUseDNS 是否使用阿里云公共DNS
     */
    fun initUtilsAndNet(
        debug: Boolean = BuildConfig.DEBUG,
        baseUrl: String = "http://terminal.timefilter.aishiguang.net/device-api/",
        deviceSerial: String = DeviceUtils.getAndroidID(),
        netConnectTimeout:Long = 30,
        netReadTimeout:Long = 30,
        netWriteTimeout:Long = 30,
        isAddDeviceSerialParam:Boolean = true,
        dnsHostNames: Array<String> = AliDnsUtils.PRELOAD_HOST_NAMES,
        isUseDNS: Boolean = true,
    ) {
        LogUtils.e("初始化jBasic Version:${BuildConfig.VERSION} isDebug=$isDebug"
            )
        isDebug = debug
        initUtils(debug)
        AliDnsUtils.init(psaApp, dnsHostNames)
        initNet(debug, baseUrl, deviceSerial, isUseDNS,netConnectTimeout,netReadTimeout,netWriteTimeout,isAddDeviceSerialParam)
    }

    private fun initUtils(debug: Boolean) {
        //崩溃重启
        // 初始化语种切换框
        MultiLanguages.init(psaApp)
        //持久化
        MMKV.initialize(psaApp)
        //工具类初始化
        Utils.init(psaApp)
        val config = LogUtils.getConfig()
        config.isLogSwitch = true
        config.globalTag = "wing"
        config.isLog2FileSwitch = true
        config.filePrefix = "PSA"
        config.saveDays = 14

        DialogX.init(psaApp)

        ToastUtils.getDefaultMaker().setBgColor(ContextCompat.getColor(this, R.color.darkgreen))
            .setTextColor(ContextCompat.getColor(this, R.color.white)).setTextSize(33)
        //初始化主板api
        myService = MyService(psaApp)
    }

    private fun initNet(
        debug: Boolean = false,
        baseUrl: String = "http://terminal.timefilter.aishiguang.net/device-api/",
        deviceSerial: String = DeviceUtils.getAndroidID(),
        isUseDNS: Boolean = true,
        netConnectTimeout:Long = 30,
        readTimeout:Long = 30,
        writeTimeout:Long = 30,
        isAddDeviceSerialParam:Boolean = true,
    ) {
        // 测试环境地址:http://terminal-dev.timefilter.aishiguang.net/device-api/
        // 生产环境地址:http://terminal.timefilter.aishiguang.net/device-api/
        // 这是接口全局域名, 可以使用NetConfig.host进行单独的修改
        NetConfig.initialize(baseUrl, this) {
            // 超时配置, 默认是10秒, 设置太长时间会导致用户等待过久
            connectTimeout(netConnectTimeout, TimeUnit.SECONDS)
            readTimeout(readTimeout, TimeUnit.SECONDS)
            writeTimeout(writeTimeout, TimeUnit.SECONDS)
            //设置缓存目录为应用缓存目录/sdcard/Android/data/app/cache，设置缓存大小为512M
            cache(Cache(externalCacheDir!!, 1024 * 1024 * 512))
            setDebug(debug)
            addInterceptor(LogRecordInterceptor(debug))
            setConverter(SerializationConverter())
            setRequestInterceptor(object : RequestInterceptor {
                override fun interceptor(request: BaseRequest) {
                    if(isAddDeviceSerialParam){
                        request.param("deviceSerial", deviceSerial)
                    }
                }
            })
            setDialogFactory() {
                BubbleDialog(it, getString(R.string.please_wait)).apply {
                    setCancelable(false)
                    setCanceledOnTouchOutside(false)
                }
            }
            if (isUseDNS) {
                LogUtils.i("使用阿里云DNS")
                dns(OkHttpDns.getInstance())
            } else {
                LogUtils.i("不使用阿里云DNS")
            }

        }
    }

}